import qs from 'qs'
import {useCallback} from "react";
interface Config extends RequestInit{
  token?:string,
  data?:object
}
const API='http://localhost:3003'

export const http=async (endpoint:string,{data,token,headers,...customConfig}:Config={})=>{
  const config={
    method:'GET',
    headers:{
      'Authorization': token ? `Bearer ${token}` : '',
      'Content-Type': data ? 'application/json' : ''
    },
    ...customConfig
  }
  if (config.method.toUpperCase()==='GET'){
    endpoint +=`?${qs.stringify(data)}`
  }else {
    config.body=JSON.stringify(data||{})
  }
  console.log(`${API}/${endpoint}`,config)
  return window.fetch(`${API}/${endpoint}`,config).then(async response=>{
    if (response.status===401){
      window.location.reload()
      return Promise.reject({'msg':'请重新登录'})
    }
    const data=await response.json()
    if (response.ok){
      return data
    }else {
      return Promise.reject(data)
    }
  })
}
export const useHttp=()=>{
  const user={token:'213'}
  return useCallback((...[endpoint,config]:Parameters<typeof http>)=>http(endpoint,{...config,token:user?.token}),[user?.token])
}